package com.example.androidroomdemo;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.androidroomdemo.DataBase.DbRoom;

/**
 * @author: tjf
 * @date: 2022-10-31
 * @desc： 数据库管理类
 */
public class DbManager {

    private static String TagL = DbManager.class.getSimpleName();

    private static final String DATABASE_NAME = "db_room";

    private static DbRoom dbRoom;

    public static synchronized DbRoom getInstance() {
        if (dbRoom == null) {
            dbRoom = Room
                    .databaseBuilder(App.Instance.getApplicationContext(), DbRoom.class, DATABASE_NAME)
                    .allowMainThreadQueries()//允许在主线程操作
                    .addCallback(new DbCreateCallBack())//增加回调监听
                    .addMigrations(Migration1_2())//增加数据库迁移
                    .build();
        }
        return dbRoom;
    }

    public static class DbCreateCallBack extends RoomDatabase.Callback {

        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            Log.e(TagL, "执行数据库创建成功: ");
        }
    }

    public static Migration Migration1_2() {
        Migration migration = new Migration(1, 2) {
            @Override
            public void migrate(@NonNull SupportSQLiteDatabase database) {
                Log.e(TagL, "执行数据库升级: ");
                // 为旧表添加新的字段
                database.execSQL("ALTER TABLE loginUser "
                        + " ADD COLUMN  gender INTEGER NOT NULL DEFAULT 0");


                //  添加新的表
//                database.execSQL("CREATE TABLE IF NOT EXISTS Book (bookName TEXT, studentId TEXT, bookId PRIMARY KEY )");
            }
        };
        return migration;
    }
}
